package com.library.common.utils.z3950;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 
 * marc
 * 
 */
public class ReadMarc {

	public void readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			ReadMarc rm = new ReadMarc();
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				try{
					rm.showMarc(tempString.getBytes("GBK"));
				}catch(Exception ee){
					//System.out.println(line+"  "+"data: "+tempString);
					System.out.println(ee);
				}
//				System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}

	}

	public void showMarc(byte[] bytes) {
		try {
//			InputStreamReader finr=new InputStreamReader(new FileInputStream(file),"GBK");
//			ByteArrayInputStream fin=new ByteArrayInputStream(filetempString.getBytes());
			// 数组bytes用于存放读取的所有字节
			// int fileSize=str.length();
			//byte bytes[] = bss;//new byte[fileSize];
//			fin.read(bytes);
			// 读取此条数据的总长度
			byte marcB[] = new byte[5];
			for (int i = 0; i < 5; i++) {
				marcB[i] = bytes[i];
			}
			String marcS = new String(marcB);
			int marcLen = Integer.parseInt(marcS);
			// System.out.println(marcLen);
			// 读取数据基地址
			byte marcB2[] = new byte[5];
			for (int i = 0; i < 5; i++) {
				marcB2[i] = bytes[i + 12];
			}
			String marcS2 = new String(marcB2);
			int dataStart = Integer.parseInt(marcS2);
			// System.out.println(dataStart);
			// 读取次目录区数据
			//
			int cmLength = dataStart - 24 - 1;
			byte marcB3[] = new byte[cmLength];
			for (int i = 0; i < cmLength; i++) {
				marcB3[i] = bytes[i + 24];
			}
			// 读取记录控制信息
			String marcS3 = new String(marcB3);
			int n = cmLength / 12;
			String controls[] = new String[n];
			for (int i = 0; i < n; i++) {
				controls[i] = marcS3.substring(i * 12, (i + 1) * 12);
				// System.out.println(controls[i]);
			}
			// 读取数据区信息
			int dataLength = marcLen - dataStart - 1;
			byte data[] = new byte[dataLength];
			for (int i = 0; i < dataLength; i++) {
				data[i] = bytes[i + dataStart];
			}
			// System.out.println(dataLength);L23
			String OKData[][] = new String[n][2];
			for (int i = 0; i < n; i++) {
				OKData[i][0] = controls[i].substring(0, 3);
				int length = Integer.parseInt(controls[i].substring(3, 7));
				int start = Integer.parseInt(controls[i].substring(7));
				//不取每个字段数据最后的结束符
				byte temp[] = new byte[length-1];
				for (int j = start; j < start + length-1; j++) {
					if(data[j]==31){
						//分隔符
						temp[j - start] = 124;
						//TODO 处理char30
//					}else if(data[j]==30){
//						temp[j - start] = 35;
					}else{
						temp[j - start] = data[j];
					}
				}
				OKData[i][1] = new String(temp,"GBK");
				System.out.print(OKData[i][0]);
				System.out.print(OKData[i][1]);

				System.out.println();
			}
			//System.out.println(new String(data));
//			fin.close();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static List<IsoChangeJson> readFileChangeJson(byte[] bytes) {
		List<IsoChangeJson> result = new ArrayList<>();
		try(BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes),"GBK"))) {
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				try {
					IsoChangeJson obj = readChangeJson(tempString.getBytes("GBK"));
					if(obj != null) {
						obj.setOrigin(tempString);
						result.add(obj);
					}
				}catch(Exception e){
					 e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static IsoChangeJson readChangeJson(byte[] bytes) {
		IsoChangeJson obj = null;
		try {
//			InputStreamReader finr=new InputStreamReader(new FileInputStream(file),"GBK");
//			ByteArrayInputStream fin=new ByteArrayInputStream(filetempString.getBytes());
			// 数组bytes用于存放读取的所有字节
			// int fileSize=str.length();
			//byte bytes[] = bss;//new byte[fileSize];
//			fin.read(bytes);
			// 读取此条数据的总长度
			byte marcB[] = new byte[5];
			for (int i = 0; i < 5; i++) {
				marcB[i] = bytes[i];
			}
			String marcS = new String(marcB);
			int marcLen = Integer.parseInt(marcS);
			// System.out.println(marcLen);
			// 读取数据基地址
			byte marcB2[] = new byte[5];
			for (int i = 0; i < 5; i++) {
				marcB2[i] = bytes[i + 12];
			}
			String marcS2 = new String(marcB2);
			int dataStart = Integer.parseInt(marcS2);
			// System.out.println(dataStart);
			// 读取次目录区数据
			//
			int cmLength = dataStart - 24 - 1;
			byte marcB3[] = new byte[cmLength];
			for (int i = 0; i < cmLength; i++) {
				marcB3[i] = bytes[i + 24];
			}
			// 读取记录控制信息
			String marcS3 = new String(marcB3);
			int n = cmLength / 12;
			String controls[] = new String[n];
			for (int i = 0; i < n; i++) {
				controls[i] = marcS3.substring(i * 12, (i + 1) * 12);
				// System.out.println(controls[i]);
			}
			// 读取数据区信息
			int dataLength = marcLen - dataStart - 1;
			byte data[] = new byte[dataLength];
			for (int i = 0; i < dataLength; i++) {
				data[i] = bytes[i + dataStart];
			}
			// System.out.println(dataLength);L23
			String OKData[][] = new String[n][2];

			// 字段标识符
			List<IsoChangeJsonTag> isoChangeJsonTags = new ArrayList<>();
			for (int i = 0; i < n; i++) {
				OKData[i][0] = controls[i].substring(0, 3);
				int length = Integer.parseInt(controls[i].substring(3, 7));
				int start = Integer.parseInt(controls[i].substring(7));
				// 指示符1
				byte[] ind1 = new byte[1];
				// 指示符2
				byte[] ind2 = new byte[1];
				//不取每个字段数据最后的结束符
				byte temp[] = new byte[length-1];
				for (int j = start; j < start + length-1; j++) {
					if(data[j]==31) {
						//分隔符
						temp[j - start] = 124;
					}
					else {
						// 指示符1
						if(j-start == 0) {
							ind1[0] = data[j];
						}
						// 指示符2
						else if(j-start == 1) {
							ind2[0] = data[j];
						}else{
							temp[j - start] = data[j];
						}
					}
				}
				OKData[i][1] = new String(temp,"GBK");
				System.out.print(OKData[i][0]);
				System.out.print(OKData[i][1]);
				System.out.println();

				// 指示符
				List<IsoChangeJsonInd> isoChangeJsonInd = new ArrayList<>();
				isoChangeJsonInd.add(new IsoChangeJsonInd("1", new String(ind1)));
				isoChangeJsonInd.add(new IsoChangeJsonInd("2", new String(ind2)));

				//子字段数据
				List<IsoChangeJsonField> isoChangeJsonField = new ArrayList<>();
				String[] split = OKData[i][1].split("\\|");
				for (String filedData : split) {
					if(! filedData.isBlank() && ! filedData.isEmpty()) {
						isoChangeJsonField.add(new IsoChangeJsonField(filedData.substring(0,1),filedData.substring(1)));
					}
				}
				// 字段标识符
				isoChangeJsonTags.add(new IsoChangeJsonTag(OKData[i][0],isoChangeJsonInd,isoChangeJsonField));
			}
			obj = new IsoChangeJson(isoChangeJsonTags);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static void main(String args[]) throws Exception {
		String file1 = "C:\\Users\\Administrator\\Documents\\WeChat Files\\wxid_2kkqqzdch1fg22\\FileStorage\\File\\2025-01\\111.iso";
//		String file2 = "C:\\Users\\Administrator\\Documents\\WeChat Files\\wxid_2kkqqzdch1fg22\\FileStorage\\File\\2025-01\\736f651b48d8e739f172f4e29834b1c5_c6d2b7359006b56f1ad30a0896162092_8(1).iso";
		ReadMarc rm = new ReadMarc();
		// rm.readFileByLines(file1);
		List<IsoChangeJson> isoChangeJsons = readFileChangeJson(Files.readAllBytes(Path.of("C:\\Users\\Administrator\\Documents\\WeChat Files\\wxid_2kkqqzdch1fg22\\FileStorage\\File\\2025-01\\111.iso")));
		System.out.println(isoChangeJsons);
	}

	@Data
	public static class IsoChangeJson {

		String origin;

		List<IsoChangeJsonTag> tags;

		public IsoChangeJson(List<IsoChangeJsonTag> tags) {
			this.tags = tags;
		}

		/**
		 * 获得数据
		 * @param tag 字段标识符
		 * @param filed 子字段标识符
		 */
		public String getData(String tag , String filed) {
			IsoChangeJsonTag isoChangeJsonTag = tags.stream().filter(tags -> tag.equals(tags.getCode())).findFirst().orElse(null);
			if(isoChangeJsonTag != null) {
				IsoChangeJsonField isoChangeJsonField = isoChangeJsonTag.getFields().stream().filter(fileds -> filed.equals(fileds.getField())).findFirst().orElse(null);
				if(isoChangeJsonField != null) {
					return isoChangeJsonField.getVal();
				}
			}
			return null;
		}


		public String format() {
			StringBuilder str = new StringBuilder();
			for (IsoChangeJsonTag tag : tags) {
				str.append(tag.getCode());
				str.append(tag.getInds().get(0).getVal());
				str.append(tag.getInds().get(1).getVal());
				str.append(tag.getFields().stream().map(f -> f.getField()+f.getVal()).collect(Collectors.joining("|")));
				str.append("\n");
			}
			return str.toString();
		}
	}

	/**
	 * 字段标识符
	 */
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	public static class IsoChangeJsonTag {

		/**
		 * 标识符
		 */
		private String code;

		private List<IsoChangeJsonInd> inds;

		private List<IsoChangeJsonField> fields;

	}

	/**
	 * 指示符
	 */
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	public static class IsoChangeJsonInd {

		private String ind;

		private String val;
	}

	/**
	 * 子字段标识&值
	 */
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	public static class IsoChangeJsonField {

		private String field;

		private String val;
	}

}
